import json
import tempfile
import os

import requests

from diet.utils.llm import llm_service
from tools.bd_text_recognition import text_recognition


def recognize_nutrition_text(image_url):
    """使用您的百度OCR类识别图片中的文字"""
    try:
        # 下载图片到临时文件
        response = requests.get(image_url)
        if response.status_code != 200:
            return None, "图片下载失败"

        # 创建临时文件
        with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_file:
            tmp_file.write(response.content)
            tmp_path = tmp_file.name

        # 使用您的百度OCR类识别文本
        ocr_result = text_recognition.main(tmp_path)

        # 解析OCR结果
        ocr_data = json.loads(ocr_result)

        # 提取识别文本
        if 'words_result' in ocr_data:
            text = '\n'.join([item['words'] for item in ocr_data['words_result']])
            return text, None
        else:
            return None, f"OCR识别失败: {ocr_data.get('error_msg', '未知错误')}"

    except Exception as e:
        return None, f"OCR处理异常: {str(e)}"
    finally:
        # 清理临时文件
        if 'tmp_path' in locals():
            try:
                os.unlink(tmp_path)
            except:
                pass

def get_nutrition_advice(nutrition_text, user_profile, net_weight):
    """使用您的LLM服务类获取营养建议"""
    try:
        print(f"开始获取营养建议，营养成分文本长度: {len(nutrition_text)}")
        print(f"用户信息: 身高{user_profile.height}cm, 体重{user_profile.weight}kg")
        print(f"净含量: {net_weight}g")
        
        # 使用您的LLM服务类
        advice, error = llm_service.get_nutrition_advice(nutrition_text, user_profile, net_weight)
        if error:
            print(f"LLM服务返回错误: {error}")
            return None, error
        
        print(f"LLM服务返回建议: {advice[:100]}...")
        return advice, None
    except Exception as e:
        print(f"LLM服务调用异常: {str(e)}")
        return None, f"LLM服务调用失败: {str(e)}"